package com.wing.actor.mailbox;

import java.util.ArrayDeque;

import com.wing.actor.message.Message;
import com.wing.actor.message.PriorityMessage;
import com.wing.actor.message.PriorityType;

/**
 * 优先级信箱
 * @author 杜祥
 * @create 2017年9月18日
 */
public class PriorityMailbox implements ActorMailbox
{
	/**
	 * 低
	 */
	private final ArrayDeque<Message> lowMailbox;
	
	
	/**
	 * 中
	 */
	private final ArrayDeque<Message> middleMailbox;
	
	
	/**
	 * 高
	 */
	private final ArrayDeque<Message> hightMailbox;
	
	
	public PriorityMailbox() 
	{
		this(32);
	}
	
	
	
	public PriorityMailbox(int minSize) 
	{
		lowMailbox = new ArrayDeque<Message>(minSize);
		
		middleMailbox = new ArrayDeque<Message>(minSize);
		
		hightMailbox = new ArrayDeque<Message>(minSize);
	}



	@Override
	public Message poll()
	{
		if(hightMailbox.size() > 0) 
		{
			return hightMailbox.poll();
		}
		
		if(middleMailbox.size() > 0) 
		{
			return middleMailbox.poll();
		}
		
		if(lowMailbox.size() > 0) 
		{
			return lowMailbox.poll();
		}
		
		return null;
	}



	@Override
	public void offer(Message message)
	{
		PriorityType priority = PriorityType.LOW;
		if(message instanceof PriorityMessage) 
		{
			priority = ((PriorityMessage)message).getPriority();
			
			if(priority == null) 
			{
				priority = PriorityType.LOW;
			}
		}
		
		switch (priority)
		{
			case LOW:
				lowMailbox.offer(message);
				break;
			case HIGHT:
				hightMailbox.offer(message);
				break;
			default:
				middleMailbox.offer(message);
				break;
		}
	}



	@Override
	public int size()
	{
		return lowMailbox.size() + middleMailbox.size() + hightMailbox.size();
	}



	@Override
	public boolean isEmpty()
	{
		return hightMailbox.isEmpty() && middleMailbox.isEmpty() && lowMailbox.isEmpty();
	}



	@Override
	public void clear()
	{
		lowMailbox.clear();
		
		middleMailbox.clear();
		
		hightMailbox.clear();
	}
	
	
}
